// store/modules/payment.js
export default {
    namespaced: true,
    state: () => ({
        showPaymentDialog: false,
        selectedOrder: null,
        selectedPaymentMethod: 'wechat',
        paymentMethods: [
            { id: 'wechat', name: '微信支付', icon: '/static/img/wechat-pay.png' },
            { id: 'alipay', name: '支付宝支付', icon: '/static/img/alipay-pay.png' },
            { id: 'balance', name: '余额支付', icon: '/static/img/balance.png' }
        ]
    }),
    mutations: {
        SET_PAYMENT_DIALOG(state, visible) {
            state.showPaymentDialog = visible;
        },
        SET_SELECTED_ORDER(state, order) {
            state.selectedOrder = order;
        },
        SET_PAYMENT_METHOD(state, methodId) {
            state.selectedPaymentMethod = methodId;
        }
    },
    actions: {
        selectPaymentMethod({ commit }, methodId) {
            commit('SET_PAYMENT_METHOD', methodId);
        },
        openPaymentDialog({ commit }, order) {
            commit('SET_SELECTED_ORDER', order);
            commit('SET_PAYMENT_DIALOG', true);
        },
        closePaymentDialog({ commit }) {
            commit('SET_PAYMENT_DIALOG', false);
        },
        confirmPayment({ state, dispatch }) {
            const { selectedOrder, selectedPaymentMethod } = state;

            if (!selectedOrder) return;

            // 模拟支付确认逻辑
            uni.showModal({
                title: '确认支付',
                content: `是否使用 ${selectedPaymentMethod === 'wechat' ? '微信' : '支付宝'} 支付 ¥${selectedOrder.totalPrice}？`,
                success: (res) => {
                    if (res.confirm) {
                        uni.showToast({ title: '支付成功', icon: 'success' });

                        // 更新订单状态为 "toReview"
                        let ordersList = uni.getStorageSync('ordersList') || [];
                        const targetIndex = ordersList.findIndex(order => order.orderId === selectedOrder.orderId);
                        if (targetIndex > -1) {
                            ordersList[targetIndex].status = 'toReview';
                            uni.setStorageSync('ordersList', ordersList);
                        }

                        dispatch('closePaymentDialog');
                        uni.$emit('updateOrders');
                    }
                }
            });
        }
    }
};
